package consumer.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

@Component
@Slf4j
public class SpringRabbitListeners {
    //接收 dlx.queue 队列的消息
    @RabbitListener(queues = "dlx.queue")
    public void listenDlxQueue(String msg) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间：" + now);
        log.info("消费者1 接收到消息: {}", msg);
        System.out.println("消费者1 接收到消息: " + msg);
    }
//接收 delay.queue 队列的消息;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "delay.queue",  durable = "true"),
            exchange = @Exchange(value = "delay.direct", type = ExchangeTypes.DIRECT,  durable = "true",delayed = "true"),//注意延迟交换机要加delayed = "true"核心
            key = "delay"
    ))
    public void listenDelayQueue(String msg) {
        log.info("{}消费者1 接收到延迟消息: {}",LocalDateTime.now(), msg);
        System.out.println(LocalDateTime.now()+"消费者1 接收到延迟消息: " + msg);
    }

    //通过注解的方式来声明交换机和队列的绑定
    @RabbitListener(bindings = @QueueBinding(
            //声明队列
            value = @Queue(value = "Direct.Queue11",  durable = "true"),
            //声明交换机
            exchange = @Exchange(value = "Direct.Exchanges", type = ExchangeTypes.DIRECT),
            //声明路由key
            key = {"pink","purple"}
    ))
    public void listenDirectQueue11(String msg) {
        log.info("消费者1 接收到消息: {}", msg);
        System.out.println("消费者Direct.Queue11 接收到消息: " + msg);
    }

    //在声明一个相同的
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "Direct.Queue22",  durable = "true"),
            exchange = @Exchange(value = "Direct.Exchanges", type = ExchangeTypes.DIRECT),
            key = {"yellow","purple"}
    ))
    public void listenDirectQueue22(String msg) {
        log.info("消费者1 接收到消息: {}", msg);
        System.out.println("消费者Direct.Queue11 接收到消息: " + msg);
    }



    //从 simple.queue 队列中接收消息
    @RabbitListener(queues = "firefly.fanout")
    public void listenSimpleQueue(Map<String, Object> msg) {
        log.info("firefly.fanout消费者接收到消息: {}", msg);
        System.out.println("firefly.fanout消费者接收到消息: " + msg);
    }

    /*
利用@RabbitListener注解，可以监听到对应队列的消息
一旦监听的队列有消息，就会回调当前方法，在方法中接收消息并消费处理消息
*/
    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage(String message) throws Exception {
        System.out.println("消费者1 接收到消息: " + message);
//故意抛出消息转换异常 - reject
        throw new MessageConversionException("故意抛出！消息转换异常");
    }
}
